# Copyright (c) 2006 Jurgen Scheible
# Application skeleton (no main loop)

#import sys
#sys.path.append('F:\\Python')
import appuifw
import e32
import ecs
import urllib
import socket
import re
from mechanize import Browser


appuifw.app.screen='large'

 
# create your application logic ...


class Amazon:
    def __init__(self,key):
        ecs.setLicenseKey(key)
        self.app_lock = e32.Ao_lock()

    def runForever(self):
        appuifw.app.menu = [
            (u"Search...", self.searchDialog),
            (u"Set Access Point", self.setAccessPoint),
            (u"AmazonCreds", self.setAmazonCredentials),

            (u"Settings", ((u"Default Acccess Point", self.setAccessPoint),
                                    (u"Amazon Credentials", self.setAmazonCredentials)))]    


        appuifw.app.title = u"Amazon.com"    
 
        appuifw.app.exit_key_handler = self.exitKeyHandler

        appuifw.app.body = appuifw.Listbox([u'foo'],self.shout)
        self.app_lock.wait()


    def searchDialog(self):
        query = appuifw.query(u"Search for..","text")
        self.queryAmazon(query)

    def setAmazonCredentials(self):
        data = [(u'Username','text', u'foo@bar.com'),(u'Password','text', u'')]

        flags = appuifw.FFormEditModeOnly
        f = appuifw.Form(data, flags)

        f.execute()
        self.userName = f[0][2]
        self.password = f[1][2]

    def queryAmazon(self,query):
        self.ensureAccess()
        self.songs = ecs.ItemSearch(query, SearchIndex='MP3Downloads')
        entries = []
        for i in range(0,10):
            song = self.songs[i]
            entries.append((
                unicode(song.Title),
                unicode(song.Creator)))

        self.lb = appuifw.Listbox(entries,self.shout)
        appuifw.app.body = self.lb

    def subitem1(self):
        print "aha"
    
    def subitem2(self):
        print "good"

    def setAccessPoint(self):
        apid = socket.select_access_point()
        f = open('e:\\apid.txt','w')
        f.write(repr(apid))
        f.close()
        appuifw.note(u"Saved default access point ", "info")
        apo = socket.access_point(apid)
        socket.set_default_access_point(apo)

    def ensureAccess(self):
        return
        try:
            f=open('e:\\apid.txt','rb')
            setting = f.read()
            apid = eval(setting)
            f.close()
            if not apid == None :
                apo = socket.access_point(apid)
                socket.set_default_access_point(apo)
            else:
                self.setAccessPoint()
        except:
            self.setAccessPoint()

    def exitKeyHandler(self):
        self.app_lock.signal()


    # define a callback function
    def sample(self):
        url = self.songs[self.lb.current()].DetailPageURL
        sock = urllib.urlopen(url)
        htmlsource = sock.read()
        m = re.search(r'a href="(/gp/dmusic/media/sample.m3u[^"]+)"', htmlsource)
        url2 = 'http://www.amazon.com' + m.group(1)
        sock = urllib.urlopen(url2)
        htmlsource = sock.read()

        url3 = htmlsource.strip()
        urllib.urlretrieve(url3, 'e:\\test.mp3')
        
        appuifw.note(u"test.mp3 downloaded! ", "info")
    
    def shout(self):
        url = self.songs[self.lb.current()].DetailPageURL

        # setup mechanize browser object with appropriate headers
        br = Browser()
        br.addheaders = [("User-agent", "Mozilla/5.0 (compatible; MyProgram/0.1)")]
        br.set_handle_robots(False)

        # goto song's page
        br.open(url)

        # click on "Buy Mp3" image
        br.follow_link(url_regex='/gp/dmusic/order/handle-buy-box.html')

        # sign in
        br.select_form(name='sign-in')
        br['email'] = self.userName
        br['password'] = self.password

        # debugging info...
        response = br.submit()
        stuff = response.read()
        f = file('dump.html','w')
        f.write(stuff)
        f.close()

        # sometimes (especially when debugging) you'll want to download
        # the same song twice.  This handles the 'warning' page
        try:
            response = br.follow_link(url_regex='/gp/dmusic/order/handle-buy-box.html')
            f = file('dump.html','w')
            f.write(response.read())
            f.close()
        except:
            print 'first time download... (or other error)'

        # click the link to download the mp3
        link = br.find_link(text='click here')
        resp = br.follow_link(link)

        # get mp3's filename
        mp3Name = resp.info().getheader('Content-Disposition').split('"')[1]
        print "downloading ... " + mp3Name

        # write the mp3
        f = file(mp3Name,'wb')
        f.write(resp.read())

        appuifw.note(u"%s downloaded! " % mp3Name, "info")


if __name__ == '__main__':
    key = '1CX5Q41115A3081P8F02'
    a = Amazon(key)
    a.runForever()
